let url_js = require("../../utils/url.js");
let common_js = require("../../utils/common.js");
let const_js = require("../../utils/const.js");
let user_js = require("../../utils/user.js");
let sys_js = require("../../utils/system.js");
let cart_js = require("../../utils/cart.js");
let ubt_js = require("../../utils/ubt.js");
let name_js = require("../../utils/ubtButtonName.js");
let api = require("../../utils/apiRequest.js");
let wxp = require("../../utils/wxp.js");
let notificationCenter = require('../../thridLib/WxNotificationCenter.js');
let en_js = require('../../utils/environment.js');

const app = getApp()
Page({
  data: {
    sysInfo: null,
    userInfo: null,
    countInfo: null, //待提货角标
    pageScrollTop: 0,
    containerTouchmove: '',
    orderMenus: [{
      title: '全部订单',
      icon: '../../images/order_order.png',
      url: '/pages/myOrder/myOrder',
      badge: '',
      isBadgeShow: false
    }, {
      title: '待付款',
      icon: '../../images/order_daifu.png',
      url: '/pages/myOrder/myOrder',
      badge: '',
      isBadgeShow: false
    }, {
      title: '待提货',
      icon: '../../images/order_daitihuo.png',
      url: '/pages/myOrder/myOrder',
      badge: '',
      isBadgeShow: false
    }, {
      title: '售后',
      icon: '../../images/order_shouhou.png',
      url: '/pages/myOrder/myOrder',
      badge: '',
      isBadgeShow: false
    }],
    serviceMenus: [{
      title: '我的拼团',
      icon: '../../images/service_pintuan.png',
      url: '/pages/myPintuan/myPintuan'
    }, {
      title: '优惠券',
      icon: '../../images/service_youhuiquan.png',
      url: '/pages/myDiscount/myDiscount'
    }, {
      title: '我要当团长',
      icon: '../../images/service_tuanzhang.png',
      url: '/pages/tobeTzFirstStep/tobeTzFirstStep'
    }, {
      title: '成为供应商',
      icon: '../../images/service_gys.png',
      url: '/pages/tobeSupplier/tobeSupplier'
    }, {
      title: '客服',
      icon: '../../images/service_kefu.png',
      url: '/pages/service/service'
    }, {
      title: '资质规则',
      icon: '../../images/service_zizhi.png',
      url: '/pages/qualification/qualification'
    }],
    goodsPropertyInfo: {
      pageShow: false, //页面展示
      dismiss: false, //手动设置隐藏，当属性页面隐藏完成后，pageShow设置false
    },
    addCartSelctedGoodsInfo: null, //当前添加购物车的商品，只有当有多种规格时有数据
    canCusNav: true,
    loginStatus: -1, //0未登录，1已经登录
    header: {
      title: '我的',
      headerbg: 'linear-gradient(#C7000B,#C74E51);',
      hiddenBack: true
    },
    pageInfo: {
      curPage: 1,
      pageSize: 10,
      noMore: false
    },
    faviroteList: [],
    shareCampaignVo: '', //老带新接口配置
  },

  onLoad: function (options) {
    //业务埋点
    ubt_js.myPageView(common_js.currentPageName(), options);
    //1.禁止转发
    wx.hideShareMenu();
    //2.注册通知
    this.registNotification();
    //3.初始化数据
    this.initData(options);
    //4.请求数据
    //4.1猜你喜欢
    this.requestToGetRecommendGuess(this.data.pageInfo.curPage, this.data.pageInfo.pageSize);
  },
  oldLeadNew() {
    let userInfo = wx.getStorageSync(en_js.userInfoKey);
    if (!userInfo || (userInfo && !userInfo.userInfo)) {
      return
    }
    api.wxRequest2(url_js.getSetting2, {}).then(res => {
      if (res.code === 200) {
        let shareCampaignVo = res.result.shareCampaignVo;
        this.setData({
          shareCampaignVo: shareCampaignVo
        })
      }
    }).catch(err => {
      common_js.log(err);
    });
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    //更新购物车数量，setTabBarBadge受限制
    cart_js.updateTabBarCount();
    //5.判断是否要显示老带新
    this.oldLeadNew();
    //刷新数量
    this.requestTogetOrderCount();
  },

  //初始化数据
  initData: function (options) {
    let tempUserInfo = user_js.userInfo();
    let menus = this.data.serviceMenus;
    if (en_js.status == 0) {
      menus.push({
        title: '扫码',
        icon: '../../images/gray_arrow.png',
        url: '/pages/scanTest/index'
      })
    }
    this.setData({
      canCusNav: app.globalData.canCusNav,
      userInfo: tempUserInfo,
      sysInfo: sys_js.systemInfo(),
      serviceMenus: menus,
      loginStatus: (user_js.isLogin() ? 1 : 0)
    });
  },

  //注册通知，当自提点切换的时候，更新数据
  registNotification: function () {
    let that = this;
    notificationCenter.addNotification(const_js.changeShopSucessNoti, that.changedShop, that);
    notificationCenter.addNotification(const_js.loginSucessNoti, that.bLoginCustomer, that);
  },

  //自提点切换
  changedShop: function () {
    //1.更新userInfo
    let tempUserInfo = user_js.userInfo();
    //reset data
    let tmpPageInfo = this.data.pageInfo;
    tmpPageInfo.curPage = 1;
    tmpPageInfo.noMore = false;
    this.setData({
      pageInfo: tmpPageInfo,
      userInfo: tempUserInfo,
      loginStatus: (user_js.isLogin() ? 1 : 0)
    });
    //2.刷新数据
    this.requestToGetRecommendGuess(this.data.pageInfo.curPage, this.data.pageInfo.pageSize, true);
  },

  //从未登录状态到登录状态
  bLoginCustomer: function () {
    //1.更新userInfo
    let tempUserInfo = user_js.userInfo();
    this.setData({
      userInfo: tempUserInfo,
      loginStatus: (user_js.isLogin() ? 1 : 0)
    });
  },

  //请求数据
  requestToGetRecommendGuess: function (curPage, pageSize, pullDownRefresh) {
    let data = {
      cityId: this.data.userInfo.ztd.cityId,
      code: user_js.getCode(),
      curPage: curPage,
      pageSize: pageSize,
      shopId: this.data.userInfo.ztd.id
    }

    api.wxRequest(url_js.recommendGuessUrl, data).then(res => {
      this.handleRecommendGuessData(res, curPage, pullDownRefresh);
      common_js.hidePageLoading(pullDownRefresh);
    }).catch(err => {
      common_js.hidePageLoading(pullDownRefresh);
      common_js.log(err);
    });
  },

  //处理返回的猜你喜欢数据
  handleRecommendGuessData: function (res, curPage, pullDownRefresh) {
    //设置数据
    let tmpList = this.data.faviroteList;
    if (pullDownRefresh) {
      tmpList = [];
    }
    //pageInfo
    let tmpPageInfo = this.data.pageInfo;
    if (res.page.pages <= curPage) {
      tmpPageInfo.noMore = true;
    } else {
      tmpPageInfo.curPage++;
    }
    //list
    if (res.result.length > 0) {
      tmpList = tmpList.concat(res.result);
      this.setData({
        pageInfo: tmpPageInfo,
        faviroteList: tmpList
      });
    } else {
      this.setData({
        pageInfo: tmpPageInfo
      });
    }
  },

  //获取数量
  requestTogetOrderCount: function () {
    let data = {
      cityId: this.data.userInfo.ztd.cityId,
      code: this.data.userInfo.code,
      shopId: this.data.userInfo.ztd.id
    }

    api.wxRequest(url_js.orderOrderCountUrl, data).then(res => {
      this.handleOrderCount(res);
    }).catch(err => {
      common_js.log(err);
    });
  },

  //处理返回的商品数量
  handleOrderCount: function (res) {
    //设置角标
    let dfkItem = this.data.orderMenus[1];
    dfkItem.badge = res.result.unPayCount;
    dfkItem.isBadgeShow = dfkItem.badge > 0;
    let dthItem = this.data.orderMenus[2];
    dthItem.badge = res.result.deliveryCount;
    dthItem.isBadgeShow = dthItem.badge > 0;

    this.setData({
      orderMenus: {
        ...this.data.orderMenus
      },
      countInfo: res.result
    })
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    //移除通知
    let that = this;
    notificationCenter.removeNotification(const_js.changeShopSucessNoti, that);
    notificationCenter.removeNotification(const_js.loginSucessNoti, that);
    // 业务埋点
    ubt_js.myPageViewOut(common_js.currentPageName());
  },

  //未登录状态下点击头像等去登录
  onUnloginView: function (e) {
    this.checkIsToLoginIndex();
  },

  //查看登录状态，未登录直接跳转登录
  checkIsToLoginIndex: function () {
    if (!user_js.isLogin()) {
      wx.navigateTo({
        url: '../loginIndex/loginIndex'
      });
      return false;
    }
    return true;
  },

  //跳转到老带新页面
  goInvite: function () {
    wx.navigateTo({
      url: '../invite/invite'
    });
  },

  // 订单点击事件
  onOrders(e) {
    if (!this.checkIsToLoginIndex()) return;
    let index = parseInt(e.currentTarget.dataset.index);
    let item = this.data.orderMenus[index];
    switch (index) {
      case 0:
        //全部订单
        wx.navigateTo({
          url: item.url
        });
        break;
      case 1:
        //待付款
        wx.navigateTo({
          url: item.url + '?segIndex=1'
        });
        break;
      case 2:
        //待提货
        wx.navigateTo({
          url: item.url + '?segIndex=2'
        });
        break;
      case 3:
        //售后
        wx.navigateTo({
          url: item.url + '?segIndex=3'
        });
        break;
      default:
        break;
    }

    //埋点
    ubt_js.myClickButton(common_js.currentPageName(), name_js.myOrder);
  },

  // 常用服务
  onServices(e) {
    if (!this.checkIsToLoginIndex()) return;
    let index = parseInt(e.currentTarget.dataset.index);
    let item = this.data.serviceMenus[index];
    switch (index) {
      case 0:
        //我的拼团
        wx.navigateTo({
          url: item.url
        });
        //埋点
        ubt_js.myClickButton(common_js.currentPageName(), name_js.myPt);
        break;
      case 1:
        //优惠券
        wx.navigateTo({
          url: item.url
        });
        //埋点
        ubt_js.myClickButton(common_js.currentPageName(), name_js.myYhq);
        break;
      case 2:
        //我要当团长
        wx.navigateTo({
          url: item.url
        });
        //埋点
        ubt_js.myClickButton(common_js.currentPageName(), name_js.myYhq);
        break;
      case 3:
        //成为供应商
        wx.navigateTo({
          url: item.url
        });
        //埋点
        ubt_js.myClickButton(common_js.currentPageName(), name_js.myYhq);
        break;
      case 4:
        //客服
        wx.navigateTo({
          url: item.url
        });
        break;
      case 5:
        //资质规则
        wx.navigateTo({
          url: item.url
        });
        break;
      case 6:
        //扫码，只会出现在测试环境
        wx.navigateTo({
          url: item.url
        });
        break;
      default:
        break;
    }
  },

  //联系团长
  contactDz: function (e) {
    if (!this.data.userInfo.ztd.mobile) {
      common_js.showToast("电话不存在！");
      return
    }
    //打电话
    wx.makePhoneCall({
      phoneNumber: this.data.userInfo.ztd.mobile
    })
  },

  //切换自提点
  onToggleZtd: function (e) {
    //埋点
    ubt_js.myClickButton(common_js.currentPageName(), name_js.myChangeZtd);

    wx.navigateTo({
      url: '../indexSearchShop/indexSearchShop'
    })
  },

  // 监听用户滑动页面事件
  onPageScroll: function (e) {
    let topY = e.scrollTop + "px";
    this.setData({
      pageScrollTop: topY
    });
  },

  //按钮点击事件
  //禁止滚动
  preventTouchMove: function () {},

  //商品属性选择确定
  onGoodsPropertyEnsure: function (e) {
    //消失
    this.onGoodsPropertyHidden();
    //添加购物车
    if (e) {
      let item = e.detail;
      //限时抢购单独判断
      if (this.data.addCartSelctedGoodsInfo.type != 0) {
        let skuItem = item.sku;
        let cartLimitCount = cart_js.limitSkuCountWithSkuId(skuItem.id);
        let isAlert = (cartLimitCount == 0) ? (item.count > skuItem.userBuyLimit) : (cartLimitCount >= skuItem.userBuyLimit);
        if (isAlert) {
          common_js.showModal("每人限购" + skuItem.userBuyLimit + "件，超过的件数将以原价支付！", null, true, null, "我知道了", () => {
            this.requestToAddCart(item.sku, this.data.addCartSelctedGoodsInfo.id, item.sku.id, item.count);
          })
          return;
        }
      }
      this.requestToAddCart(item.sku, this.data.addCartSelctedGoodsInfo.id, item.sku.id, item.count);
    }
  },

  //商品属性选择
  onGoodsPropertyHidden: function (e) {
    let tmpGoodsPropertyInfo = this.data.goodsPropertyInfo;
    tmpGoodsPropertyInfo.pageShow = false;
    tmpGoodsPropertyInfo.dismiss = false,
      this.setData({
        containerTouchmove: '',
        goodsPropertyInfo: tmpGoodsPropertyInfo
      });
  },

  //隐藏商品属性页面
  onHidePropertyPageView: function (e) {
    let tmpGoodsPropertyInfo = this.data.goodsPropertyInfo;
    tmpGoodsPropertyInfo.dismiss = true;
    this.setData({
      goodsPropertyInfo: tmpGoodsPropertyInfo
    });
  },

  //添加商品
  onAddGoods: function (e) {
    if (!this.checkIsToLoginIndex()) return;

    let index = e.currentTarget.dataset.index;
    let item = this.data.faviroteList[index];
    if (item.skuList && item.skuList.length > 1) {
      if (item.dimensions.length == 0) {
        common_js.showToast("商品多规格属性不存在！");
        return;
      }
      //多规格,选择规格加入购物车
      //展示多规格商品
      let tmpGoodsPropertyInfo = this.data.goodsPropertyInfo;
      tmpGoodsPropertyInfo.pageShow = true;
      this.setData({
        addCartSelctedGoodsInfo: item,
        goodsPropertyInfo: tmpGoodsPropertyInfo,
        containerTouchmove: 'preventTouchMove'
      });
    } else {
      //单一规格,直接添加购物车
      if (item.skuList == 0) {
        common_js.showToast("商品sku不存在");
        return;
      }
      //限时抢购单独判断
      if (item.type != 0) {
        let skuItem = item.skuList[0];
        let cartLimitCount = cart_js.limitSkuCountWithSkuId(skuItem.id);
        let isAlert = (cartLimitCount == 0) ? (item.count > skuItem.userBuyLimit) : (cartLimitCount >= skuItem.userBuyLimit);
        if (isAlert) {
          common_js.showModal("每人限购" + skuItem.userBuyLimit + "件，超过的件数将以原价支付！", null, true, null, "我知道了", () => {
            this.requestToAddCart(item.skuList[0], item.id, item.skuList[0].id, 1);
          })
          return;
        }
      }
      this.requestToAddCart(item.skuList[0], item.id, item.skuList[0].id, 1);
    }

    //埋点
    ubt_js.myClickButton(common_js.currentPageName(), name_js.myAddGoods);
  },

  //增加购物车
  requestToAddCart: function (skuItem, productId, skuId, num) {
    let data = {
      cityId: this.data.userInfo.ztd.cityId,
      code: user_js.getCode(),
      num: num,
      productId: productId,
      shopId: this.data.userInfo.ztd.id,
      skuId: skuId
    };
    api.wxRequest(url_js.cartAddUrl, data).then(res => {
      this.handleAddCartData(res, skuItem, skuId, num);
    }).catch(err => {
      common_js.log(err);
    });
  },

  //处理添加购物车
  handleAddCartData: function (res, skuItem, skuId, num) {
    cart_js.addCart(skuItem, skuId, num);
    common_js.showToast("添加购物车成功");
  },

  //商品详情
  onGoodsDetail: function (e) {
    let index = e.currentTarget.dataset.index;
    let item = this.data.faviroteList[index];
    wx.navigateTo({
      url: '../goodsDetails/goodsDetails?productId=' + item.id
    });
  },

  // 打开地图
  onMap() {
    // 获取设置
    wxp.openLocation({
      latitude: this.data.userInfo.ztd.geoLat,
      longitude: this.data.userInfo.ztd.geoLon
    }).then(res => {}).catch(err => {})
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    //1.reset data
    let tmpPageInfo = this.data.pageInfo;
    tmpPageInfo.curPage = 1;
    tmpPageInfo.noMore = false;
    this.setData({
      pageInfo: tmpPageInfo
    });
    //3.request
    //3.1猜你喜欢
    this.requestToGetRecommendGuess(tmpPageInfo.curPage, tmpPageInfo.pageSize, true);
    //3.2购物车数量
    this.requestTogetOrderCount();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    if (this.data.pageInfo.noMore) return;
    this.requestToGetRecommendGuess(this.data.pageInfo.curPage, this.data.pageInfo.pageSize);
  },
})